package com.zxbit.flash.ui.activity.login;

import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.CountDownTimer;
import android.text.SpannableString;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.zxbit.flash.R;
import com.zxbit.flash.base.BaseTitleActivity;
import com.zxbit.flash.common.Constant;
import com.zxbit.flash.common.RouterMap;
import com.zxbit.flash.mvpview.RegisterMvpView;
import com.zxbit.flash.mvpview.VerifyCodeMvpView;
import com.zxbit.flash.network.Urls;
import com.zxbit.flash.permission.IPermisson;
import com.zxbit.flash.permission.Permission;
import com.zxbit.flash.presenter.RegisterPresenter;
import com.zxbit.flash.presenter.VerifyCodePresenter;
import com.zxbit.flash.response.BlankResponse;
import com.zxbit.flash.utils.LocationUtils;
import com.zxbit.flash.utils.StringUtils;
import com.zxbit.flash.utils.ToastUtils;
import com.zxbit.flash.view.dialog.RandomCodeDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

@Route(name = "注册", path = RouterMap.REGISTER_PAGE)
public class RegisterActivity extends BaseTitleActivity implements IPermisson, RegisterMvpView, VerifyCodeMvpView {

    @BindView(R.id.phone_numer_text)
    EditText phoneNumerText; // 手机号
    @BindView(R.id.verify_code_text)
    EditText verifyCodeText; // 验证码
    @BindView(R.id.password_text)
    EditText passwordText; // 密码
    @BindView(R.id.do_acquire_voice_code)
    TextView doAcquireVoiceCode; // 语音验证
    @BindView(R.id.do_acquire_verify_code)
    TextView doAcquireVerifyCode; // 短信验证
    @BindView(R.id.check_agreement)
    CheckBox checkAgreement; // 阅读协议

    private RandomCodeDialog mRandomCodeDialog;
    private RegisterPresenter registerPresenter;
    private VerifyCodePresenter verifyCodePresenter;
    private CustomerCountDownTimer countDownTimer;
    private boolean isStartCountDown = false; //是否开始倒计时

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
    }

    @Override
    protected void onUIReady() {
        registerPresenter = new RegisterPresenter(this);
        verifyCodePresenter = new VerifyCodePresenter(this);
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_resgister;
    }

    @OnClick({R.id.do_acquire_voice_code, R.id.do_acquire_verify_code, R.id.tv_check_agreement_text,
            R.id.register_btn, R.id.register_to_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.do_acquire_voice_code:
                // 语音验证
                if (!isStartCountDown) {
                    getVerifyCode(0);
                }
                break;
            case R.id.do_acquire_verify_code:
                // 短信验证码
                if (!isStartCountDown) {
                    showRandomCodeDialog();
                }
                break;
            case R.id.tv_check_agreement_text:
                checkAgreement.setChecked(!checkAgreement.isChecked());
                break;
            case R.id.register_btn:
                String verifyMsg = verifyParams();
                if (StringUtils.isEmpty(verifyMsg)) {
                    // 请求位置信息
                    Permission permission = new Permission(RegisterActivity.this, RegisterActivity.this);
                    permission.uploadLocation();
                } else {
                    ToastUtils.showShort(this, verifyMsg);
                }
                break;
            case R.id.register_to_login:
                finish();
                break;
        }
    }

    @OnCheckedChanged({R.id.show_psw_text, R.id.check_agreement})
    public void OnCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.show_psw_text:
                if (isChecked) {
                    passwordText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
            case R.id.check_agreement:
                if (isChecked) {
                    ARouter.getInstance()
                            .build(RouterMap.WEB_VIEW_PAGE)
                            .withInt(Constant.PARAMS_TYPE, Constant.WEB_TYPE_REGISTER)
                            .withString(Constant.PARAMS_URL, Urls.REGISTER_AGREEMENT_URL)
                            .navigation();
                }
                break;
        }
    }

    private void showRandomCodeDialog() {
        if (mRandomCodeDialog == null) {
            mRandomCodeDialog = new RandomCodeDialog(RegisterActivity.this, R.style.normal_dialog)
                    .setRandomClickListener(new RandomCodeDialog.RandomClickListener() {
                        @Override
                        public void onConfirmClick() {
                            String editCode = mRandomCodeDialog.getEditCode();
                            String realCode = mRandomCodeDialog.getRealCode();
                            if (realCode.equals(editCode)) {
                                mRandomCodeDialog.dismiss();
                                getVerifyCode(1);
                            } else {
                                mRandomCodeDialog.rebuildCode();
                                ToastUtils.showShort(RegisterActivity.this, getResources().getString(R.string.register_random_error));
                            }
                        }
                    });
        }
        mRandomCodeDialog.show();
    }

    /**
     * 获取验证码
     *
     * @param type 1 短信  0语音
     */
    private void getVerifyCode(int type) { // 获取短信验证码
        String phoneNum = phoneNumerText.getText().toString();
        if (StringUtils.isEmpty(phoneNum)) {
            ToastUtils.showShort(RegisterActivity.this, getStringResource(R.string.register_user_name_is_null));
            return;
        }
        verifyCodePresenter.getVoiceCode(phoneNum, type);
        showLoadingView();
    }

    @Override
    public void onSuccess(int result) {
        registerPresenter.registerRequest(phoneNumerText.getText().toString().trim(),
                passwordText.getText().toString().trim(), verifyCodeText.getText().toString().trim(), "1");
        showLoadingView();
    }

    @Override
    public void onGetDataNext(BlankResponse registerResponse) {
        if (registerResponse.getStatus() == Constant.HTTP_OK) {
            // 上报经纬度
            Location location = LocationUtils.getLocation(RegisterActivity.this);
            if (location == null) {
                onGetDataNext(phoneNumerText.getText().toString().trim());
            } else {
                registerPresenter.uploadLocation(location, phoneNumerText.getText().toString().trim());
            }
        } else {
            dismissLoadingView();
            if (!StringUtils.isEmpty(registerResponse.getMessage())) {
                ToastUtils.showShort(RegisterActivity.this, registerResponse.getMessage());
            }
        }
    }

    @Override
    public void onGetDataNext(String phoneNum) {
        dismissLoadingView();
        jumpToLoginPage(phoneNum);
    }

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }

    @Override
    public void onGetDataNext(BlankResponse response, int type) {
        dismissLoadingView();
        if (response.getStatus() == Constant.HTTP_OK) {
            if (type == 1) {
                processCountDownView(doAcquireVerifyCode,
                        new SpannableString(getStringResource(R.string.register_acquire_verity_code)));
            } else {
                processCountDownView(doAcquireVoiceCode,
                        new SpannableString(getStringResource(R.string.register_acquire_voice_code)));
            }
        } else {
            if (!StringUtils.isEmpty(response.getMessage())) {
                ToastUtils.showShort(RegisterActivity.this, response.getMessage());
            }
        }
    }

    private class CustomerCountDownTimer extends CountDownTimer {
        private TextView textView;
        private Drawable background;
        private SpannableString endStrRes;

        public void updateTextView(TextView textView, SpannableString strSpan) {
            this.textView = textView;
            this.endStrRes = strSpan;
            background = this.textView.getBackground();

        }

        public CustomerCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (this.textView == null) return;
            textView.setText((millisUntilFinished / 1000 + 1) + "s");
        }

        @Override
        public void onFinish() {
            if (this.textView == null) return;
            isStartCountDown = false;
            if (background != null) {
                this.textView.setBackground(background);
            }
            if (this.endStrRes != null) {
                this.textView.setText(endStrRes);
            }
            textView.setEnabled(true);
        }
    }

    private String verifyParams() {
        String phoneNum = phoneNumerText.getText().toString();
        String psw = passwordText.getText().toString();
        String verifyCode = verifyCodeText.getText().toString();
        if (StringUtils.isEmpty(phoneNum)) {
            return getApplicationContext().getResources().getString(R.string.register_user_name_is_null);
        } else if (StringUtils.isEmpty(psw)) {
            return getApplicationContext().getResources().getString(R.string.register_psw_is_null);
        } else if (StringUtils.isEmpty(verifyCode)) {
            return getApplicationContext().getResources().getString(R.string.register_verify_code_is_null);
        } else if (!checkAgreement.isChecked()) {
            return getStringResource(R.string.register_not_agree);
        }
        return null;
    }

    private void jumpToLoginPage(String phoneNum) {
        ToastUtils.showShort(RegisterActivity.this, getStringResource(R.string.register_suc_and_go_to_login));
        ARouter.getInstance().build(RouterMap.LOGIN_PAGE)
                .withString(Constant.USER_NAME, phoneNum.trim()).navigation();
        finish();
    }

    /**
     * 处理倒计时view
     */
    private void processCountDownView(final TextView countDownView, final SpannableString stringSpan) {
        isStartCountDown = true;
        if (countDownTimer == null) {
            countDownTimer = new CustomerCountDownTimer(59 * 1000, 1000);
        } else {
            countDownTimer.cancel();
        }
        countDownTimer.updateTextView(countDownView, stringSpan);
        countDownView.setEnabled(false);

        countDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}
